package G1;

public class ArrayHashMap<K ,V> {
	private ArrayList<Hashlist>[] maps;
	private int capacity;
	private int childcnt;
	
	public ArrayHashMap(int capacity) {
		this.capacity = capacity;
		childcnt = 0;
		maps = (ArrayList<Hashlist>[]) new ArrayList[capacity]; 
		for(int i=0; i<capacity; i++) {
			maps[i] = new ArrayList<Hashlist>(); 
		}
	}
	private int genKey(K key){
		return key.hashCode()%capacity;
	}
	private boolean contain(K key){
		ArrayList<Hashlist> tmp = maps[genKey(key)];
		if(tmp.isEmpty())
			return false;
		for(int i=0; i<tmp.size();i++)
		{
			if(tmp.get(i).getKey().equals(key))
			{
				return true;
			}
		}
		return false;
	}
	public void printall(){
		for(int i=0;i<maps.length;i++){
			if(!maps[i].isEmpty()){
				for(int j=0;j<maps[i].size();j++)
				System.out.print(maps[i].get(j).key+",");
			}
		}
	}
	public ArrayList<V> toList(){
		ArrayList<V> tmp = new ArrayList<>();
		for(int i=0;i<maps.length;i++){
			if(!maps[i].isEmpty()){
				for(int j=0;j<maps[i].size();j++)
					tmp.add((V) maps[i].get(j).getElement());
			}
		}
		return tmp;
	}
	
	
	private int indexof(K key){
		ArrayList<Hashlist> tmp = maps[genKey(key)];
		if(tmp.isEmpty())
			return -2;
		for(int i=0; i<tmp.size();i++)
		{
			if(tmp.get(i).getKey().equals(key))
			{
				return i;
			}
		}
		return -1;
	}
	public boolean put(K key, V element){
		Hashlist tmp = new Hashlist(key, element);
		int index = indexof(key);
		if(index>=0) {
			return false;
		} else {
			childcnt++;
			maps[genKey(key)].add(tmp);
			return true;
		}
	}
	
	public boolean remove(K key){
		int index = indexof(key);
		if(index>=0) {
			maps[genKey(key)].remove(index);
			childcnt--;
			return true;
		}
		return false;
	}
	
	public boolean change(K key, V element){
		int index = indexof(key);
		if(index>=0) {
			Hashlist tmp = new Hashlist(key, element);
			maps[genKey(key)].set(index, tmp);
			childcnt--;
			return true;
		}
		return false;
	}
	
	public V get(K key) throws EmptyNodeException{
		int index = indexof(key);
		if(index>=0)
			return (V)maps[genKey(key)].get(index).getElement();
		else
			throw new EmptyNodeException("It's don't have hash node");
	}
	public boolean isEmpty() {
		return (childcnt==0);
	}
}